package com.example.twoscroolview.view

import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.graphics.Paint
import android.util.AttributeSet
import android.view.View
import android.webkit.WebStorage
import androidx.core.graphics.drawable.toBitmap
import com.example.twoscroolview.R
import android.graphics.drawable.BitmapDrawable

import android.graphics.drawable.Drawable




class PhotoView : View {
    val paint by lazy {
        Paint()
    }

    var originalOffsetX = 0f
    var originalOffsetY = 0f
    lateinit var mBitmap: Bitmap

    constructor(context: Context) : super(context) {

    }

    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
    }

    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(
        context,
        attrs,
        defStyleAttr
    )

    init {

        createBitMap()
    }

    fun createBitMap() {
        mBitmap =      drawableToBitmap(resources.getDrawable(R.mipmap.meinv))
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)

        canvas.drawBitmap(mBitmap, originalOffsetX, originalOffsetY, paint)
    }

    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)

        originalOffsetX = (width - mBitmap.width) / 2f
        originalOffsetY = (height - mBitmap.height) / 2f
    }

    fun drawableToBitmap(drawable: Drawable): Bitmap {
        if (drawable is BitmapDrawable) {
            return drawable.bitmap
        }
        val bitmap =
            Bitmap.createBitmap(drawable.intrinsicWidth, drawable.intrinsicHeight, Bitmap.Config.ARGB_8888)
        val canvas = Canvas(bitmap)
        drawable.setBounds(0, 0, canvas.width, canvas.height)
        drawable.draw(canvas)
        return bitmap
    }
}